package com.nage.multiplayer;

import java.io.BufferedInputStream;
import java.io.IOException;

import com.nage.engine.GameGraph;
import com.nage.engine.GameGraphBuilder;

import android.util.Log;

public class MultiplayerInputThread extends Thread {

	BufferedInputStream in;
	MultiplayerSystem ms;
	private byte[] buf;
	boolean connected;

	public MultiplayerInputThread(MultiplayerSystem ms) {
		this.ms = ms;
		try {
			in = new BufferedInputStream(ms.m_Socket.getInputStream());
			connected = true;
			Log.i("MultiplayerInputThread", "InputStream connected.");
		} catch (IOException e) {
			Log.e("MultiplayeInputThread", "Cannot find remote connection: "
					+ e.getMessage());
			connected = false;
		}

		buf = new byte[1024];
	}
 
	@Override
	public void run() { 
		while (connected) {
			try {
				int read;
				while ((read = in.read(buf)) != -1) {
					//Log.d("MultiplayerInputThread", "Recieved " + read + " bytes.");
					if(buf[0]==RemoteInput.sPACKET) {
						RemoteInput p = new RemoteInput();
						while(RemoteInput.expand(buf, p)) {
							Log.d("MultiplayerInputThread", "Current time: "+System.currentTimeMillis());
							Log.d("MultiplayerInputThread", "Packet created: "+p.toString());
							Log.d("MultiplayerInputThread", read - RemoteInput.i +" bytes left." );
							ms.sendToInputSystem(p);
							if(read - RemoteInput.i < 10) {
								RemoteInput.i = 0;
								break;
							}
							p = new RemoteInput();
						}
							//Log.d("MultiplayerInputThread", "Current time: "+System.currentTimeMillis());
							//Log.d("MultiplayerInputThread", "Final packet created: "+p.toString());
						Log.d("MultiplayerInputThread", "Packet recieved. Time sent: "+p.time+". Time now: "+System.currentTimeMillis());
						ms.sendToInputSystem(p);
					} else if (buf[0]==GameGraphBuilder.sGAME_GRAPH_PACKET) {
						GameGraph graph = GameGraphBuilder.expand(buf);
						ms.simulation.updateGraph(graph);
					}

				}
			} catch (Exception e) {
				Log.e("MultiplayerInputThread",
						e.getMessage()+": Killing MultiplayerSystem");
				connected = false;
				try {
					in.close();
				} catch (IOException e2) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} 
		}
	}
	
	public void close() {
		connected = false;
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
